("本脚本为子进程，用于积累性写入一个Array或者Object");
import Fs from "fs-extra";
let path = "";
const arr: any[] = [];
const obj = {};

export type JsonRows = any[] | Object;

export interface JsonAccumArg0 {
  path?: string;
  rows?: JsonRows;
  id?: string;
}

export interface JsonAccumResult {
  complete: boolean;
  id?: string;
}

/**
 * 向主进程发送数据
 */
function postMsg(...args: any[]) {
  // @ts-ignore
  process.send(...args);
}

function handleData({ path: filePath, rows, id }: JsonAccumArg0): void {
  if (filePath) {
    path = filePath;
  }
  if (rows) {
    if (rows instanceof Array) {
      arr.push(...rows);
      Fs.outputJSONSync(path, arr, { spaces: "\t" });
    } else {
      Object.assign(obj, rows);
      Fs.outputJSONSync(path, obj, { spaces: "\t" });
    }
    let result: JsonAccumResult = { complete: true, id };
    postMsg(result);
  }
}

process.on("message", handleData);
